<template>
	<view class="spc-page1 content">

		<u-navbar :fixed="false" :autoBack="true" title="SPC 控制图看板" left-icon-color="#fff" :safeAreaInsetTop="true">
		</u-navbar>

		<!-- 时间与图表选择器 -->
		<view class="filter-section">
			<u-tabs :list="chartOptionsData" :current="selectedChartIndex" @change="changeChartTab"></u-tabs>
		</view>

		<view class="flex-auto">


			<!-- 图表展示区 -->
			<view class="chart-card" v-if="selectedChartIndex == 0">
				<text class="chart-title">控制图</text>
				<SpcXRChart :data="tableData" :spec="{ usl: 1.0, lsl: 0.8, target: 0.9 }"></SpcXRChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 1">
				<text class="chart-title">样本运行图</text>
				<SpcYBChart :data="tableData" :spec="{ usl: 1.0, lsl: 0.8, target: 0.9 }">></SpcYBChart>

			</view>

			<view class="chart-card" v-if="selectedChartIndex == 2">
				<text class="chart-title">CPK 分析图</text>
				<SpcCPKChart :data="tableData" :spec="{ usl: 1.0, lsl: 0.8, target: 0.9 }"></SpcCPKChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 3">
				<text class="chart-title">均值运行图</text>
				<SpcJZChart :data="tableData" :spec="{ usl: 1.0, lsl: 0.8, target: 0.9 }"></SpcJZChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 4">
				<text class="chart-title">正态分布图</text>
				<SpcZTChart :data="tableData"></SpcZTChart>
			</view>

			<view class="chart-card" v-if="selectedChartIndex == 5">
				<text class="chart-title">合格率趋势图</text>
				<SpcHGChart :data="tableData"></SpcHGChart>
			</view>



			<uni-table border stripe emptyText="暂无更多数据" style="max-height: 500rpx;">
				<!-- 表头行 -->

				<!-- <uni-thead > -->
				<uni-tr class="sticky-header">
					<uni-th align="left" width="40px" class="sticky-col">
						<text>No.</text>
					</uni-th>
					<uni-th align="left" width="200rpx">
						<text>抽检时间</text>
					</uni-th>
					<uni-th align="left" v-for="index in filteredData[0].samples.length" width="100rpx">
						<text>样本{{index}}</text>
					</uni-th>
					<uni-th align="left" width="100rpx">
						<text>平均值</text>
					</uni-th>
					<uni-th align="left" width="100rpx">
						<text>状态</text>
					</uni-th>
				</uni-tr>
				<!-- </uni-thead> -->
				<!-- 表格数据行 -->
				<!-- <uni-tbody> -->
				<uni-tr v-for="(item, i) in filteredData" :key="i">
					<uni-td class="sticky-col">
						<text>{{i+1}}</text>
					</uni-td>
					<uni-td>
						<text>{{item.inspectTime}}</text>
					</uni-td>
					<uni-td v-for="(row,ind) in item.samples" :key="ind">
						<text>{{row}}</text>
					</uni-td>
					<uni-td>
						<text>{{item.mean}}</text>
					</uni-td>
					<uni-td>
						<text>{{item.status}}</text>
					</uni-td>
				</uni-tr>
				<!-- </uni-tbody> -->
			</uni-table>


		</view>
	</view>
</template>

<script>
	import spcUtils from '@/common/comFun/spc-utils.js'
	import rawData from '@/static/MorkData/spc-data.js'
	import SpcXRChart from './components/ChartByXR.vue'
	import SpcYBChart from './components/ChartByYB.vue'
	import SpcJZChart from './components/ChartByJZ.vue'
	import SpcZTChart from './components/ChartByZT.vue'
	import SpcCPKChart from './components/ChartByCPK.vue'
	import SpcHGChart from './components/ChartByHG.vue'


	export default {
		components: {
			SpcXRChart,
			SpcYBChart,
			SpcJZChart,
			SpcZTChart,
			SpcCPKChart,
			SpcHGChart
		},
		data() {
			return {
				startTime: '2018-07-30 15:53:53',
				endTime: '2018-08-29 15:53:53',
				filteredData: [],
				chartOptionsData: [{
						name: '控制图'
					},
					{
						name: '样本运行图'
					},
					{
						name: 'CPK 分析图'
					},
					{
						name: '均值运行图'
					},
					{
						name: '正态分布图'
					},
					{
						name: '合格率趋势图'
					},
				],
				selectedChartIndex: 0,

				tableData: [],

			}
		},
		onLoad() {
			this.applyFilter()
		},
		methods: {
			/**
			 * 计算每条记录中样本数组的统计信息，包括：
			 * - 平均值（mean）
			 * - 极差（range）
			 * - 标准差（stdDev，样本标准差）
			 * - 最大值（max）
			 * - 最小值（min）
			 * 
			 * 保留小数位：
			 * - mean：4 位
			 * - range、max、min：3 位
			 * - stdDev：6 位
			 * 
			 * 统计说明：
			 * 1. mean（平均值）：
			 *    mean = Σx / n
			 * 
			 * 2. range（极差）：
			 *    range = max - min
			 * 
			 * 3. stdDev（样本标准差）：
			 *    stdDev = sqrt( Σ(xi - mean)² / (n - 1) )
			 *    说明：用 n - 1 是为了得到“样本标准差”的无偏估计
			 * 
			 * 4. max, min：
			 *    样本的最大值、最小值
			 */
			calculateStatsPerRecord(data) {
				return data.map(record => {
					const values = record.samples;
					const n = values.length;

					if (!Array.isArray(values) || n === 0) {
						// 无有效样本值，返回空统计字段
						return {
							...record,
							mean: null,
							range: null,
							stdDev: null,
							max: null,
							min: null
						};
					}

					// 1. 计算平均值（mean）
					const sum = values.reduce((acc, val) => acc + val, 0);
					const mean = sum / n;

					// 2. 计算最大值、最小值、极差（range）
					const max = Math.max(...values);
					const min = Math.min(...values);
					const range = max - min;

					// 3. 计算样本标准差（stdDev）
					//    方差 = Σ(xi - mean)^2 / (n - 1)
					//    标准差 = sqrt(方差)
					let variance = 0;
					if (n > 1) {
						variance = values.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / (n - 1);
					}
					const stdDev = Math.sqrt(variance);

					// 4. 返回带有统计信息的新记录
					return {
						...record,
						mean: Number(mean.toFixed(4)), // 平均值保留4位小数
						range: Number(range.toFixed(3)), // 极差保留3位小数
						stdDev: Number(stdDev.toFixed(6)), // 标准差保留6位小数
						max: Number(max.toFixed(3)), // 最大值保留3位小数
						min: Number(min.toFixed(3)) // 最小值保留3位小数
					};
				});
			},
			applyFilter() {
				let filteredData = rawData.filter(d => {
					return new Date(d.inspectTime) >= new Date(this.startTime) && new Date(d.inspectTime) <=
						new Date(this.endTime)
				});
				let mapData = this.calculateStatsPerRecord(filteredData);
				console.log(this.filteredData);
				this.filteredData = JSON.parse(JSON.stringify(mapData));

				console.log(this.filteredData);
				this.tableData = JSON.parse(JSON.stringify(mapData));
			},
			changeChartTab(item) {
				console.log(item);
				let that = this;
				setTimeout(() => {
					that.selectedChartIndex = item.index;
				}, 300);
			},
		}
	}
</script>


<style scoped>
	.spc-page {
		background: #f9f9f9;
		color: #333;
		padding: 20rpx;
	}

	.sticky-col {
		position: sticky;
		left: 0;
		background: #fff;
		/* 避免透明重叠 */
		z-index: 10;
	}

	.sticky-header {
		position: sticky;
		top: 0;
		/* 固定在顶部 */
		z-index: 100;
		/* 确保表头在滚动时覆盖数据行 */
		background-color: #fff;
		/* 背景色避免透明 */
	}

	.navbar {
		padding: 30rpx 20rpx;
		background: #fff;
		text-align: center;
	}

	.title {
		font-size: 36rpx;
		color: #333;
	}

	.filter-section {
		background: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.time-selector {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.chart-selector {
		margin-top: 10rpx;
	}

	.time-item {
		flex: 1;
	}

	.picker-view {
		padding: 10rpx;
		background: #fff;
		color: #333;
		border-radius: 8rpx;
	}

	.btn {
		padding: 10rpx 20rpx;
		margin-top: 20rpx;
	}

	.chart-card {
		background: #fff;
		margin-bottom: 40rpx;
		padding: 20rpx;
		border-radius: 16rpx;
	}

	.chart-title {
		font-size: 28rpx;
		margin-bottom: 10rpx;
		color: #09f;
	}

	.table-container {
		margin-top: 40rpx;
		background: #fff;
		color: #333;
		border-radius: 16rpx;
		overflow: auto;
	}

	.table-row {
		display: flex;
		padding: 20rpx;
		justify-content: space-between;
		border-bottom: 1px solid #333;
	}

	.table-header {
		background: #fff;
		color: #333;
		font-weight: bold;
	}
</style>